import React, { useState, useRef } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';

const TextDesign: React.FC = () => {
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [processedImage, setProcessedImage] = useState<string | null>(null);
  const [textDescription, setTextDescription] = useState<string>('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const history = useHistory();

  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Validate file type
      if (!file.type.match('image.*')) {

        return;
      }

      // Validate file size (10MB limit)
      if (file.size > 10 * 1024 * 1024) {
        return;
      }

      const reader = new FileReader();
      reader.onloadstart = () => {
        setUploadProgress(0);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null); // Reset processed image when new image is uploaded
      };
      reader.readAsDataURL(file);
    }
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
    
    const file = event.dataTransfer.files[0];
    if (file) {
      if (!file.type.match('image.*')) {

        return;
      }

      if (file.size > 10 * 1024 * 1024) {
        return;
      }

      const reader = new FileReader();
      reader.onloadstart = () => {
        setUploadProgress(0);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleGenerate = async () => {
    if (!selectedImage || !textDescription.trim()) {
      return;
    }
    
    // 检查用户是否有足够的积分
    const currentCreditsText = parseInt(localStorage.getItem('credits') || '0');
    if (currentCreditsText < 1) {
      history.push('/buy-credits'); // Redirect to BuyCredits page
      return;
    }

    setIsProcessing(true);
    try {
      // 将 base64 图片数据转换为 Blob
      const base64Data = selectedImage.split(',')[1];
      const blob = await fetch(`data:image/jpeg;base64,${base64Data}`).then(res => res.blob());

      // 创建 FormData 对象...

      
      const formData = new FormData();
      const google_id = localStorage.getItem('google_id');
      formData.append('google_id', google_id || '');
      formData.append('model_id', '5');
      formData.append('img', selectedImage );
      formData.append('content', textDescription);
      // 发送请求到后端
      const response = await fetch('https://aa.jstang.cn/api/ai/call', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      setProcessedImage(data.data);
      // 原图 找下那个Room Designer这个逻辑 怎么调用的原图 ，
      // setSelectedImage(data.originalImage); // Removed this line to keep the user's original image
    
      
      // 消费积分 (Ensure currentCredits is defined here if you uncomment)
      // const newCredits = currentCreditsText - 1; // Use the variable defined above
      // localStorage.setItem('credits', newCredits.toString());
      
    } catch (error) {
      console.error('Error processing image:', error);
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">Text-Guided Room Designer</h1>
          <p className="text-xl text-gray-600">Upload your room photo and describe your dream space</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left Column - Upload and Text Description */}
          <div className="space-y-8">
            {/* Image Upload Section */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5 }}
              className="bg-white rounded-xl shadow-lg p-6"
            >
              <div className="mb-6">
                <label className="block text-lg font-medium text-gray-700 mb-2">
                  Upload Your Room Photo
                </label>
                <div 
                  className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer"
                  onClick={() => fileInputRef.current?.click()}
                  onDragOver={handleDragOver}
                  onDrop={handleDrop}
                >
                  <div className="space-y-1 text-center">
                    {selectedImage ? (
                      <div className="relative">
                        <img
                          src={selectedImage}
                          alt="Uploaded room"
                          className="max-h-96 w-auto mx-auto rounded-lg"
                        />
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setSelectedImage(null);
                            setProcessedImage(null);
                          }}
                          className="absolute top-2 right-2 bg-red-500 text-white p-2 rounded-full hover:bg-red-600 transition-colors"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                          </svg>
                        </button>
                      </div>
                    ) : (
                      <>
                        <svg
                          className="mx-auto h-12 w-12 text-gray-400"
                          stroke="currentColor"
                          fill="none"
                          viewBox="0 0 48 48"
                        >
                          <path
                            d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                            strokeWidth={2}
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                        <div className="flex text-sm text-gray-600">
                          <span className="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500">
                            Upload a file
                          </span>
                          <p className="pl-1">or drag and drop</p>
                        </div>
                        <p className="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
                      </>
                    )}
                    {uploadProgress > 0 && uploadProgress < 100 && (
                      <div className="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                        <div
                          className="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
                          style={{ width: `${uploadProgress}%` }}
                        ></div>
                      </div>
                    )}
                  </div>
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  className="hidden"
                  accept="image/*"
                  onChange={handleImageUpload}
                />
              </div>
            </motion.div>

            {/* Text Description */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="bg-white rounded-xl shadow-lg p-6"
            >
              <label className="block text-lg font-medium text-gray-700 mb-4">
                Describe Your Dream Space
              </label>
              <textarea
                value={textDescription}
                onChange={(e) => setTextDescription(e.target.value)}
                placeholder="Describe how you want your room to look. For example: 'A modern minimalist living room with white walls, wooden floors, and plants.'"
                className="w-full h-40 p-4 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
              />

              <div className="mt-6">
                <button
                  onClick={handleGenerate}
                  disabled={!selectedImage || !textDescription.trim() || isProcessing}
                  className={`w-full py-3 px-4 rounded-lg text-white font-medium transition-colors ${
                    !selectedImage || !textDescription.trim() || isProcessing
                      ? 'bg-gray-400 cursor-not-allowed'
                      : 'bg-blue-500 hover:bg-blue-600'
                  }`}
                >
                  {isProcessing ? (
                    <div className="flex items-center justify-center">
                      <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      Processing...
                    </div>
                  ) : (
                    <>Generate Design <span className="ml-2 text-sm opacity-80">(Cost: 1 credit)</span></>
                  )}
                </button>
              </div>
            </motion.div>
          </div>

          {/* Right Column - Preview or Before/After Comparison */}
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
            className="bg-white rounded-xl shadow-lg p-6"
          >
            {processedImage ? (
              <>
                <h3 className="text-lg font-medium text-gray-700 mb-4">Before & After</h3>
                <div className="space-y-8">
                  <div>
                    <p className="text-sm text-gray-500 mb-2">Original</p>
                    <div className="relative w-full h-[250px] rounded-lg overflow-hidden shadow-lg">
                      <img
                        src={selectedImage || ''}
                        alt="Original room"
                        className="w-full h-full object-contain bg-gray-100"
                      />
                    </div>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500 mb-2">Redesigned</p>
                    <div className="relative w-full h-[250px] rounded-lg overflow-hidden shadow-lg">
                      <img
                        src={processedImage}
                        alt="Redesigned room"
                        className="w-full h-full object-contain bg-gray-100"
                      />
                    </div>
                    {processedImage && (
                      <button
                        onClick={() => {
                          const link = document.createElement('a');
                          link.href = processedImage; 
                          link.download = 'text_redesigned_room.png'; // Or a more dynamic name
                          document.body.appendChild(link);
                          link.click();
                          document.body.removeChild(link);
                        }}
                        className="mt-4 px-6 py-2 bg-green-500 text-white rounded-lg font-medium hover:bg-green-600 transition-colors"
                      >
                        Download Image
                      </button>
                    )}
                  </div>
                </div>
              </>
            ) : (
              <div className="space-y-8">
                <div>
                  <p className="text-sm text-gray-500 mb-2">Preview</p>
                  <div className="relative w-full h-[250px] rounded-lg overflow-hidden shadow-lg">
                    <img
                      src="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80"
                      alt="Preview"
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                      <div className="text-center text-white">
                        <p className="text-2xl font-bold mb-2">Your Design Preview</p>
                        <p className="text-lg">Upload a room photo and describe your vision</p>
                      </div>
                    </div>
                  </div>
                </div>
                <div>
                  <p className="text-sm text-gray-500 mb-2">How it works</p>
                  <div className="relative w-full h-[250px] rounded-lg overflow-hidden shadow-lg">
                    <img
                      src="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80"
                      alt="How it works"
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                      <div className="text-center text-white">
                        <p className="text-2xl font-bold mb-2">Text-Guided Design</p>
                        <ol className="text-left text-lg space-y-2">
                          <li>1. Upload your room photo</li>
                          <li>2. Describe your dream space</li>
                          <li>3. Click Generate Design</li>
                        </ol>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </motion.div>
        </div>
      </div>
    </div>
  );
};

export default TextDesign;